package com.pzhu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzhu.common.constant.Constant;
import com.pzhu.model.entity.Career;
import com.pzhu.model.entity.Staff;
import com.pzhu.model.entity.UserRole;
import com.pzhu.model.entity.Wage;
import com.pzhu.model.help.PageBean;
import com.pzhu.model.help.ResponseResult;
import com.pzhu.model.vo.StaffInfoVo;
import com.pzhu.service.CareerService;
import com.pzhu.service.StaffService;
import com.pzhu.service.WageService;
import com.pzhu.utils.BeanCopyUtils;
import com.pzhu.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * @Author : zqh
 * @Date : 2024/1/3 0003 下午 4:22
 * @Version: 1.0
 */
@Api(tags = "工作人员")
@RestController
@RequestMapping("/staff")
public class StaffController {

    @Autowired
    private StaffService staffService;
    @Autowired
    private CareerService careerService;
    @Autowired
    private WageService wageService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation("查询所有人员信息")
    @PostMapping("/list")
    public ResponseResult list(@RequestBody PageBean pageBean){

        String query=pageBean.getQuery().trim();

        Page<Staff> page = staffService.page(
                new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),
                new QueryWrapper<Staff>()
                        .like(StringUtil.isNotEmpty(query), "username", query)
                        .or()
                        .like(StringUtil.isNotEmpty(query),"job_number",query));

        List<Staff> list = page.getRecords();

        List<StaffInfoVo> staffInfoVos = BeanCopyUtils.copyBeanList(list, StaffInfoVo.class);

        for (StaffInfoVo staffInfoVo : staffInfoVos) {
            Career career = careerService.getById(staffInfoVo.getCareerId());
            staffInfoVo.setCareer(career.getName());
        }


        Map<String,Object> map=new HashMap<>();
        map.put("staffList",staffInfoVos);
        map.put("total",page.getTotal());
        return ResponseResult.ok(map);
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @ApiOperation("重置用户密码")
    @GetMapping("/resetPassword/{id}")
//    @PreAuthorize("hasAuthority('system:user:edit')")
    @ApiImplicitParam(name = "id",value = "用户ID",required = true)
    public ResponseResult resetPassword(@PathVariable(value = "id")Long id){
        Staff staffInfo = staffService.getById(id);
        staffInfo.setPassword(bCryptPasswordEncoder.encode(Constant.DEFAULT_PASSWORD));
        staffInfo.setUpdateTime(new Date());
        staffService.updateById(staffInfo);
        return ResponseResult.ok();
    }

    /**
     * 添加或者修改
     * @param staff
     * @return
     */
    @ApiOperation("添加或修改用户")
    @PostMapping("/save")
//    @PreAuthorize("hasAuthority('system:user:add')"+"||"+"hasAuthority('system:user:edit')")
    public ResponseResult save(@RequestBody @Valid Staff staff){
        if(staff.getId()==null || staff.getId()==-1){
            staff.setCreateTime(new Date());
            staff.setPassword(bCryptPasswordEncoder.encode("123456"));
            //员工号  首先查找最大的工号+1
            Map<String, Object> map = staffService.getMap(
                    new QueryWrapper<Staff>()
                            .select("IFNULL(MAX(job_number),0) as jobNumber"));

            System.err.println(map);
            Integer jobNumber = new Integer(map.get("jobNumber").toString());
            staff.setJobNumber(++jobNumber);
            staffService.save(staff);

            //设置基础工资
            Wage wage = new Wage();
            wage.setJobNumber(++jobNumber);
            wage.setStar(Constant.BASE_STAR);
            wage.setName(staff.getUsername());
            wage.setAge(staff.getAge());

            wage.setCareer(careerService.getById(staff.getCareerId()).getName());
            wage.setWage(Constant.BASE_WAGE);
            wage.setCreateTime(new Date());

            wageService.save(wage);
        }else{
            staff.setUpdateTime(new Date());
            staffService.updateById(staff);
        }
        return ResponseResult.ok();
    }

    @ApiOperation("详细信息")
    @GetMapping("/detail/{id}")
    @ApiImplicitParam(name = "id",value = "工作人员ID",required = true)
    public ResponseResult detail(@PathVariable(value = "id") Long id){
        return staffService.detail(id);
    }

    @Transactional
    @ApiOperation("批量删除用户")
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public ResponseResult delete(@RequestBody Long[] ids){
        staffService.removeByIds(Arrays.asList(ids));
        return ResponseResult.ok();
    }
}
